<?php
/**
 * Created by PhpStorm.
 * User: kb356
 * Date: 2016/12/2
 * Time: 13:49
 * 个推推送队列gpushA,gpushB,gpushC,gpushD,gpushQ四个队列中的数据分四个文件建立定时任务
 * gpushQ为群推 频率每分钟一次 每次最多 五条
 * 其他为单个推送频率每两秒一次 单个进程最长时间为1000s
 */
namespace soa\gpush;

use artisan\queue;
use artisan\config;
use artisan\db;
use soa\gpush\gpush;
class send
{
    private $a = 0;
    private $gpush;
    private $db;
    //接收队列名
    public function __construct($queuename)
    {
        if (!in_array($queuename, ['A', 'B', 'C', 'D', 'Q'])) {
            echo '请输入队列名A,B,C,D，Q';
            die;
        }
        $this->db=db::connect('users')->table('tbl_user_channel');
        $this->popmsg($queuename);
    }
    //循环取出数据
    public function popmsg($queuename)
    {
        $starttime = time();
        while ($info = queue::pop('gpush' . $queuename)) {
            $info = json_decode($info, true);
            $this->send($info);
            //时间过长杀死该进程 防止死循环
            time() - $starttime > 1000 && die;
        }
    }
    //调用推送接口
    public function send($info)
    {   //logDebug($info,'g_push');
        if ($this->gpush) {
            $gpush = $this->gpush;
        } else {
            $this->gpush =$gpush = new \soa\gpush\gpush\gpush();
        }
        if ($info['device'] != '') {

            if($info['platform'] == 'ios'){
                $cid=$info['device']['client_id'];
                $sql ="select badge from tbl_user_channel where device_type='ios' and client_id='{$cid}'";
                $re = $this->db->query($sql);
                $info['badge']=(int)$re[0]['badge']+1;
                $sql ="update tbl_user_channel set badge='{$info['badge']}'  where device_type='ios' and client_id='{$cid}'";
                $this->db->query($sql);
            }
            $rep = $gpush->pushMessageToSingle($info,$info['platform']);
        } else {
            //群推->每次最多连续推送五条  ()频率限制
            $this->a++;
            $this->a >= 6 && die;
            $rep = $gpush->pushMessageToApp($info);
        }


        // 预留   用于处理推送结果（群推）   可在官网查看
        //            if(isset($rep['result'])&&$rep['result'] == 'ok')
        //            {
        //            }else{
        //            }
        // var_dump($rep);
    }
}